package renda.dao.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Repository;

import renda.dao.BaseDAO;
import renda.dao.UserDAO;
import renda.pojo.Users;

@Repository("userDao")
public class UserDAOImpl extends BaseDAO implements UserDAO, InitializingBean {

	private Map<Integer, String> idNameMap = new HashMap<Integer, String>();

	@Override
	@SuppressWarnings("unchecked")
	public void afterPropertiesSet() throws Exception {
		List list = getTemplate().find("from Users");
		List<Users> list2 = list;
		for (Users users : list2) {
			idNameMap.put(users.getUid(), users.getUname());
		}
	}

	// public void get(Users user) {
	// user.setUserIntegral(0);
	// user.setIsEmailVerify("no");
	// user.setEmailVerifyCode(VerifyCodeUtil.getVerifyCode());
	// user.setLastLoginTime(new SimpleDateFormat("yyyy-MM-dd kk:mm:ss").format(new Date(System.currentTimeMillis())));
	// user.setLastLoginIp(ServletActionContext.getRequest().getRemoteAddr());
	// getTemplate().save(user);
	// }

	@SuppressWarnings("unchecked")
	public Users get(Users user) {
		List list = getTemplate().find("from Users where uname = ? ", user == null ? "" : user.getUname());
		if (list != null && list.size() > 0) {
			return (Users) list.get(0);
		}
		return null;
		// List list = getTemplate().findByExample(user);
		// Users user1 = new Users();
		// if(list.size()>0){
		// user1 = (Users)list.get(0);
		// }
		// return (user1);
	}

	public Users save(Users user) {
		getTemplate().save(user);
		return user;
	}

	@Override
	public String getNameById(Integer id) {
		// List list = getTemplate().find("select uname from Users where uid = ?", id == null ? -1 : id);
		// if (list != null && list.size() > 0) {
		// return (String) list.get(0);
		// }
		String name = idNameMap.get(id);
		return StringUtils.isNotBlank(name) ? name : "";
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<String> getNamesByIds(List<Integer> ids) {
		if (ids != null && ids.size() > 0) {
			List list = getTemplate().find("select uname from Users where uid in ?", ids);
			if (list != null && list.size() > 0) {
				return list;
			}
		}
		return Collections.emptyList();
	}

}
